<template>
    <div>
        <Button type="primary" ghost icon="md-add" @click="handleOpenCreate">添加</Button>
        <Button @click="handleDeleteMultiple" type="error" ghost icon="md-trash" class="ivu-ml-8" v-show="selectedData.length">批量删除</Button>
        <div class="ivu-inline-block ivu-fr">
            <Dropdown @on-click="handleChangeTableSize" trigger="click">
                <Tooltip class="ivu-ml" content="密度" placement="top">
                    <i-link>
                        <Icon type="md-list" />
                    </i-link>
                </Tooltip>
                <DropdownMenu slot="list">
                    <DropdownItem name="default" :selected="tableSize === 'default'">默认</DropdownItem>
                    <DropdownItem name="large" :selected="tableSize === 'large'">宽松</DropdownItem>
                    <DropdownItem name="small" :selected="tableSize === 'small'">紧凑</DropdownItem>
                </DropdownMenu>
            </Dropdown>
            <Tooltip class="ivu-ml" :content="tableFullscreen ? '退出全屏' : '全屏'" placement="top">
                <i-link @click.native="handleFullscreen">
                    <Icon :custom="tableFullscreen ? 'i-icon i-icon-exit-full-screen' : 'i-icon i-icon-full-screen'" />
                </i-link>
            </Tooltip>
            <Tooltip class="ivu-ml" content="刷新" placement="top">
                <i-link @click.native="handleRefresh">
                    <Icon custom="i-icon i-icon-refresh" />
                </i-link>
            </Tooltip>
            <Dropdown trigger="click">
                <Tooltip class="ivu-ml" content="列设置" placement="top">
                    <i-link>
                        <Icon type="md-options" />
                    </i-link>
                </Tooltip>
                <DropdownMenu slot="list">
                    <div class="ivu-p-8">列展示</div>
                    <Divider size="small" class="ivu-mt-8 ivu-mb-8" />
                    <li class="ivu-dropdown-item" v-for="item in columns" :key="item.title" v-if="item.title" @click="item.show = !item.show">
                        <Checkbox v-model="item.show"></Checkbox>
                        <span>{{ item.title }}</span>
                    </li>
                </DropdownMenu>
            </Dropdown>
        </div>
        <Table
            ref="table"
            :columns="tableColumns"
            :data="list"
            :loading="loading"
            :size="tableSize"
            class="ivu-mt"
            @on-row-click="handleClickRow"
            @on-sort-change="handleSortChange"
            @on-select="handleSelect"
            @on-select-cancel="handleSelectCancel"
            @on-select-all="handleSelectAll"
            @on-select-all-cancel="handleClearSelect"
        >
            <template slot-scope="{ row }" slot="status">
                <Badge v-if="row.status === 1" color="green" text="正常" />
                <Badge v-if="row.status === 0" color="red" text="停用" />
            </template>
            <template slot-scope="{ row }" slot="updatedTime">
                <div>{{new Date(row.updatedTime).format("yyyy-MM-dd hh:mm")}}</div>
            </template>
            <template slot-scope="{ row }" slot="action">
                <div @click.stop.prevent>
                    <a type="text" @click="handleEdit(row.id)">编辑</a>
                    <Divider type="vertical" />
                    <a type="text" @click="handleDelete(row.id)">删除</a>
                </div>
            </template>
        </Table>
        <div class="ivu-mt ivu-text-center">
            <Page
                :total="total"
                :current.sync="current"
                show-total
                show-sizer
                show-elevator
                :page-size="limit"
                @on-change="handleChangePage"
                @on-page-size-change="handleChangePageSize"
            />
        </div>
        <Drawer
                :styles="drawer.styles"
                v-model="drawer.show"
                :title="drawer.type === 'edit' ? '编辑组织' : drawer.type === 'new' ? '添加组织' : '组织信息'"
                width="560"
                :transfer="false"
        >
            <table-form :entityId="entityId" :drawerType="drawer.type" v-if="drawer.show" @saveFinished="handleFormSaveFinished"></table-form>
        </Drawer>
    </div>
</template>
<script>
    import { GetList,Delete } from '@api/org';
    import { cloneDeep } from 'lodash';
    import tableForm from './tableForm';

    export default {
        name:'org-organization',
        components:{tableForm},
        data () {
            return {
                columns: [
                    {
                        type: 'selection',
                        width: 55,
                        align: 'center',
                        show: true
                    },
                    {
                        title: '组织简称',
                        key: 'orgName',
                        sortable: 'custom',
                        minWidth: 140,
                        show: true
                    },
                    {
                        title: '组织全称',
                        key: 'fullName',
                        sortable: 'custom',
                        minWidth: 200,
                        show: true
                    },
                    {
                        title: '组织类型',
                        key: 'orgTypeName',
                        minWidth: 80,
                        show: true
                    },
                    {
                        title: '联系电话',
                        key: 'tel',
                        minWidth: 120,
                        show: true
                    },
                    {
                        title: '排序值',
                        key: 'sort',
                        minWidth: 60,
                        show: true
                    },
                    {
                        title: '状态',
                        key: 'status',
                        slot: 'status',
                        minWidth: 60,
                        show: true
                    },
                    {
                        title: '更新时间',
                        key: 'updatedTime',
                        sortable: 'custom',
                        slot: 'updatedTime',
                        minWidth: 200,
                        show: true
                    },
                    {
                        title: '更新人员',
                        key: 'updatedUserId',
                        minWidth: 120,
                        show: false
                    },
                    {
                        title: '操作',
                        key: 'action',
                        slot: 'action',
                        minWidth: 120,
                        align: 'center',
                        fixed: 'right',
                        show: true
                    }
                ],
                loading: false,
                list: [],
                selectedData: [],
                current: 1,
                limit: 10,
                total: 0,
                sortType: 'normal', // 当前排序类型，可选值为：normal（默认） || asc（升序）|| desc（降序）,
                sortKey: '', // 排序列的 key
                tableSize: 'default',
                tableFullscreen: false,
                tableFormReady: false,
                entityId:null,
                drawer: {
                    show: false,
                    type: 'edit', // edit || read || new
                    styles: {
                        height: 'calc(100% - 55px)',
                        overflow: 'auto',
                        paddingBottom: '53px',
                        position: 'static'
                    }
                },
            }
        },
        computed: {
            // 动态设置列
            tableColumns () {
                const columns = [...this.columns];
                return columns.filter(item => item.show);
            },
            offset () {
                return (this.current - 1) * this.limit;
            }
        },
        methods: {
            getData () {
                if (this.loading) return;
                this.loading = true;
                // 下面的 params 是获取的表单查询参数
                //const params = this.$parent.$parent.$refs.form.data;
                GetList({
                    pageIndex: this.current, // 起始页
                    pageSize: this.limit, // 查询数量
                    sortType: this.sortType,
                    sortKey: this.sortKey
                }).then(res => {
                    if(res.errcode!=0){
                        this.$Message.error(res.msg);
                        return;
                    }
                    var result=res.data;
                    this.handleClearSelect();
                    this.list = result.items;
                    this.total = result.totalCount;
                    this.loading = false;
                });
            },
            // 改变表格尺寸
            handleChangeTableSize (size) {
                this.tableSize = size;
            },
            // 表格全屏
            handleFullscreen () {
                this.tableFullscreen = !this.tableFullscreen;
                this.$emit('on-fullscreen', this.tableFullscreen);
            },
            // 刷新表格数据
            handleRefresh () {
                this.getData();
            },
            // 切换页码
            handleChangePage (page) {
                this.current = page;
                this.getData();
            },
            // 根据删除的数据条数切换页码
            handleChangePage2 (deleteCount) {                
                let newPage=1;
                if(this.current>1){
                    if(this.list.length-deleteCount>0)
                        newPage=this.current;
                    else
                        newPage=this.current-1;
                }
                this.current = newPage;
                this.getData();
            },
            // 切换每页条数
            handleChangePageSize (size) {
                this.current = 1;
                this.limit = size;
                this.getData();
            },
            // 排序
            handleSortChange ({ key, order }) {
                this.current = 1;
                this.sortType = order;
                this.sortKey = key;
                this.getData();
            },
            // 选中一项，将数据添加至已选项中
            handleSelect (selection, row) {
                this.selectedData.push(row);
            },
            // 取消选中一项，将取消的数据从已选项中删除
            handleSelectCancel (selection, row) {
                const index = this.selectedData.findIndex(item => item.id === row.id);
                this.selectedData.splice(index, 1);
            },
            // 当前页全选时，判断已选数据是否存在，不存在则添加
            handleSelectAll (selection) {
                selection.forEach(item => {
                    if (this.selectedData.findIndex(i => i.id === item.id) < 0) {
                        this.selectedData.push(item);
                    }
                });
            },
            // 清空所有已选项
            handleClearSelect () {
                this.selectedData = [];
            },
            // 查找单项信息
            handleGetItem (id) {
                return this.list.find(item => item.id === id);
            },
            // 删除
            handleDelete (id) {
                if (this.loading) return;
                this.$Modal.confirm({
                    title: '删除确认',
                    content: `您确认要删除组织<strong>${this.handleGetItem(id).name}</strong>？`,
                    loading: true,
                    onOk: () => {
                        Delete(id).then(res => {
                            if(res.errcode!=0){
                                this.$Message.error(res.msg);
                                return;
                            }
                            this.$Modal.remove();                            
                            // 完成后刷新数据
                            this.handleClearSelect();
                            this.handleChangePage2(1);
                        });
                    }
                });
            },
            // 批量删除
            handleDeleteMultiple () {
                if (this.loading) return;
                const ids = this.selectedData.map(item => item.id);
                const names = this.selectedData.map(item => item.name);
                this.$Modal.confirm({
                    title: '删除确认',
                    content: `您确认要删除组织<strong>${names}</strong>？`,
                    loading: true,
                    onOk: () => {
                        Delete(ids.join(',')).then(res => {
                            if(res.errcode!=0){
                                this.$Message.error(res.msg);
                                return;
                            }
                            this.$Modal.remove();
                            // 完成后刷新数据
                            this.handleClearSelect();
                            this.handleChangePage2(ids.length);
                        });
                    }
                });
            },
            // 编辑
            handleEdit (id) {
                //this.$Date(this.userInfo.birthday).format('YYYY-MM-DD');
                this.entityId=id;
                this.drawer.type = 'edit';
                this.drawer.show = true;
                this.handleInitTablForm();
            },
            // 组织详情
            handleClickRow (row) {
                //this.userInfo = cloneDeep(this.handleGetItem(row.id));
                this.entityId=row.id;
                this.drawer.type = 'read';
                this.drawer.show = true;
                //this.handleInitTablForm();
            },
            // 添加组织
            handleOpenCreate () {
                this.entityId=null;
                this.drawer.type = 'new';
                this.drawer.show = true;
                //this.handleInitTablForm();
            },
            handleInitTablForm () {
                // this.tableFormReady = false;
                // this.$nextTick(() => {
                //     this.userInfoFormReady = true;
                // });
            },
            //表单组件保存数据完成
            handleFormSaveFinished(){
                this.drawer.show = false;
                // 完成后刷新数据
                this.handleClearSelect();
                this.handleChangePage(1);                
            }
        },
        mounted(){
            this.getData();
        }
    }
</script>
<style lang="less">
    .page-sys-user{
        &-drawer{
            &-footer{
                width: 100%;
                position: absolute;
                bottom: 0;
                left: 0;
                border-top: 1px solid #e8e8e8;
                padding: 10px 16px;
                text-align: right;
                background: #fff;
            }
            &-form{
                .ivu-input[disabled], fieldset[disabled] .ivu-input, .ivu-select-disabled .ivu-select-selection{
                    background-color: #fff;
                    color: inherit;
                }
                &-region{
                    .i-region-transfer{
                        width: 270px;
                    }
                    .i-region-drop-main{
                        width: 270px !important;
                        height: 200px;
                        overflow: auto;
                        column-count: 2;
                        &-item{
                            line-height: normal;
                        }
                    }
                }
            }
        }
    }
</style>
